<?php
class Cart {
	var $id;
	var $ct_session_id;
	var $order; // STRING
	var $error;
	//Current column
	var $col=0;
	//Ordinate of column start
        var $totalcost = 0;
	var $y0;
	
	var $pdfs; // array containing any pdfs created for the order.
	
	var $orderIds; // array to store all the order IDS
	var $orderNumber;
	
function showCart($sessionId) {
	
//	require ('system/db/dbconnect.class.php');
	$DB = new Connection();

        //Create an array to hold the cost data
        $fullcost = array();
	
	$sql = "SELECT * FROM `cart` WHERE `ct_session_id` = '".$sessionId."'";
	$result = $DB->selectQuery($sql);
	$html .= "<ul class=\"accordion\">";
	if( mysql_num_rows($result) > 0){
	require_once("system/orders/order.class.php");
	$ORDER = new Order();
		while ($cartObj = mysql_fetch_array($result)){
		 
		$html .= "<li>";
		$ORDER = unserialize($cartObj[2]);
                //Pass in the cost data from the unserialized object
                $fullcost[] = $ORDER->totalCost;
		$html .= $ORDER->displayOrderForCart("cart", $cartObj[0]);
			
		}
		$html .= "</li>";
	
	}else{
		$html .= "<p>Your Cart Is Empty</p>";
	}
	

        //Calculate the total cost
        foreach ($fullcost as $key) {
            $totalcost = $totalcost + $key;
        }

        return $html;
}

function fullPrice($sessionId) {
    $DB = new Connection();

    //Create an array to hold the cost data
    $fullcost = array();
    $html = "";

    $sql = "SELECT * FROM `cart` WHERE `ct_session_id` = '".$sessionId."'";
    $result = $DB->selectQuery($sql);
    if( mysql_num_rows($result) > 0){
        require_once("system/orders/order.class.php");
            $ORDER = new Order();
                while ($cartObj = mysql_fetch_array($result)){

                    $ORDER = unserialize($cartObj[2]);
                    //Pass in the cost data from the unserialized object
                    $fullcost[] = $ORDER->totalCost;

                }

    }else{

    }

    //Calculate the total cost
    foreach ($fullcost as $key) {
        $totalcost = $totalcost + $key;
    }

	$html .= "<b style=\"font-size: 20px;\">Costs</b><br /><br />";
    $html .= "Current Cost: &pound;".number_format($totalcost, 2)."<br />\n";
    	$plusvat = ($totalcost / 15.5);
    $html .= "VAT @ 15.5%: &pound;".number_format($plusvat, 2)."<br />\n";
    	$fullcost = $totalcost + $plusvat;
    $html .= "<b>Total Cost: &pound;".number_format($fullcost, 2)."</b><br />\n";
    echo $html;
}

function setPurchaseOrderNumber($number){
	$this->orderNumber = $number;
}

function getPurchaseOrderNumber(){
	return $this->orderNumber;
}
	
function addToCart(){
	
	$sql = "INSERT INTO `cart` VALUES (NULL, '".$_SESSION['username']."', '".$_SESSION['order']."');";

	$DB = new Connection();

	$result = $DB->selectQuery($sql);
	
		if ($result){
		
			header("Location:viewcart.php");
			
		}else{
		
			header("Location:home.php");
			
		}
	}
	
	function removeFromCart($ct_session_id, $id){
	
		$sql = "DELETE FROM `cart` WHERE `id` = ".$id.";";

	$DB = new Connection();

	$result = $DB->selectQuery($sql);
	
		if ($result){
		
			header("Location:viewcart.php");
			
		}else{
		
			header("Location:home.php");
		}	
	}
	
	function showMiniCart($sessionId = NULL){
	
		if($sessionId == NULL){
			$amount = '0';
		}else{
		$DB = new Connection();
	
		$sql = "SELECT * FROM `cart` WHERE `ct_session_id` = '".$sessionId."'";
		$result = $DB->selectQuery($sql);
		$amount = mysql_num_rows($result);
		}
		
		$html = "<div id=\"miniCart\">\n";
		$html .= "<p>Orders in cart: ".$amount."</p>\n";
		$html .= "<p><a href=\"viewcart.php\">View Cart</a></p>\n";
		$html .= "</div>\n";
		
		return $html;
	
	}
	
	
	function showDeliveryCost($sessionId){
	/*$DB = new Connection();
	
	$sql = "SELECT * FROM `cart` WHERE `ct_session_id` = '".$sessionId."'";
	$result = $DB->selectQuery($sql);
	$amount = mysql_num_rows($result);
	
	switch ($amount) {
    case 0:
        $deliveryCost =  0;
        break;
    case 1:
        $deliveryCost =  9.75;
        break;
    case 2:
        $deliveryCost =  7.50;
        break;
    case 3:
        $deliveryCost =  6.00;
        break;
    case 4:
        $deliveryCost =  5.00;
        break;
    default:
    	$deliveryCost =  4.50;
    	break;
	}
	
	$totalDeliveryCost = $amount * $deliveryCost;
	
	
	$html .= "<h3>Delivery Costs</h3>";
	$html .= "<p>1 Order - &pound;9.75 each.</p>";
	$html .= "<p>2 Order - &pound;7.50 each.</p>";
	$html .= "<p>3 Order - &pound;6.00 each.</p>";
	$html .= "<p>4 Order - &pound;5.00 each.</p>";
	$html .= "<p>5+ Order - &pound;4.50 each.</p>";
	$html .= "<p>Orders above xxKg will require additional deliveries.</p>";
	$html .= "<p>We will confirm with you the total cost of delivery before your order is printed.</p>";
	$html .= "<p>Current Cost Per Item: &pound;".number_format($deliveryCost, 2)."</p>";
	$html .= "<p>Total Delivery Cost: &pound;".number_format($totalDeliveryCost, 2)."</p>";
	*/
	$deliveryCost =  9.75;
	$html .= "<h3>Delivery Costs</h3>";

	
	$html .= "<p>Orders above 10Kg will require additional deliveries.</p>";
	$html .= "<p>For orders over 10Kg, we will confirm with you the total cost of delivery before your order is printed.</p>";
	$html .= "<p>Total Delivery Cost: &pound;".number_format($deliveryCost, 2)."</p>";
	
	
	return $html;
}


	
	function getOrderFromCart($sessionId){
	
	// return orders from database as an array
		$ORDERARRAY = array();
		$DB = new Connection();
	
		$sql = "SELECT * FROM `cart` WHERE `ct_session_id` = '".$sessionId."'";
		$result = $DB->selectQuery($sql);
	
		if( mysql_num_rows($result) > 0){
		require_once("system/orders/order.class.php");
			while ($cartObj = mysql_fetch_array($result)){
			$ORDER = unserialize($cartObj[2]);
			$ORDERARRAY[] = $ORDER;
			}
	
	}
		return $ORDERARRAY;
	}
	
	function processOrder($ORDERARRAY){
	
	
	
		$DB = new Connection();
		$this->orderIds = array();
	
		$TRANS_SQL ="START TRANSACTION";
		$result = $DB->selectQuery($TRANS_SQL);
		
		
		// get user info
		$USER_SQL = "SELECT * FROM `user_login` LEFT JOIN `user_profile` ON user_login.id = user_profile.loginId WHERE user_login.id = ".$_SESSION['userId']."";
		
		if (!$result = $DB->selectQuery($USER_SQL)){ $this->error = 1; }
		
		$USEROBJ = mysql_fetch_object($result);
		$address = $USEROBJ->address1."\n".$USEROBJ->address2."\n".$USEROBJ->city."\n".$USEROBJ->postcode;
		$date = date("Y-m-d"); 
		$ops_manager = 	$USEROBJ->opsManager;
		
		// get the total cost
		$total_price = 0;
		foreach ($ORDERARRAY as $key => $val){
		$order = $val;
		$total_price = $total_price + $order->totalCost;
		}
		
		
		$SQL = "INSERT INTO `reports` VALUES (";
		// id
		$SQL .= " '', ";
		// order Number
		$SQL .= " '1', ";
		// user name
		$SQL .= " '".$_SESSION['username']."', ";
		// LOB
		$SQL .= " '".addslashes($address)."', ";
		// address
		$SQL .= " '".$_SESSION['lob']."', ";
		// date
		$SQL .= " '".$date."', ";
		// ops manager
		$SQL .= " '".$ops_manager."',";
		
		// total_price
		$SQL .= " '".$total_price."' ";
		
		$SQL .= ")";
		
	//	$result = $DB->selectQuery($SQL);
		if (!$result = $DB->selectQuery($SQL)){ $this->error = 1; }
		
	$LAST_ID = "SELECT `id` FROM `reports` ORDER BY `id` DESC LIMIT 1";
	$result = $DB->selectQuery($LAST_ID);
	$LAST_ID_ARRAY = mysql_fetch_assoc($result);
	$LAST_ID = $LAST_ID_ARRAY['id'];
	
	
	foreach ($ORDERARRAY as $key => $val){
		$order = $val;
		
		// ENTER ORDER INTO DATABASE
		
		// grab the lob from a db
		
		$sectorSQL = "SELECT `nameOfSector` FROM `sectors` WHERE `id` = '".$order->getSector()."'";
		$sectorresult = $DB->selectQuery($sectorSQL);
		while($row = mysql_fetch_array($sectorresult)){
			$sectorName = $row['nameOfSector'];
		}
		
		$ORDER_SQL = "INSERT INTO `orders` VALUES (";
		// id
		$ORDER_SQL .= " '', ";
		// order Number
		$ORDER_SQL .= " '".$LAST_ID."', ";
		// name of promo
		$ORDER_SQL .= " '".$order->nameOfPromotion."', ";
		// order
		$ORDER_SQL .= " '".serialize($order)."', ";
		// price
		$ORDER_SQL .= " '".$order->totalCost."', ";
		// extras
		$ORDER_SQL .= " '".$sectorName."' ";
		$ORDER_SQL .= ")";
				
	//	$result = $DB->selectQuery($ORDER_SQL);
		if (!$result = $DB->selectQuery($ORDER_SQL)){
			$this->error = 1;
		}else{
		$LAST_ID_ORDER = "SELECT `id` FROM `orders` ORDER BY `id` DESC LIMIT 1";
		$result = $DB->selectQuery($LAST_ID_ORDER);
		$LAST_ORDER_ID_ARRAY = mysql_fetch_assoc($result);
		$this->orderIds[] = $LAST_ORDER_ID_ARRAY['id'];
		}

		}
		
		if($this->error != 1){
		$emailSent = $this->sendorder($ORDERARRAY,$USEROBJ);
		}
		if($emailSent){
		$TRANS_SQL ="COMMIT";
		$result = $DB->selectQuery($TRANS_SQL);
		
		// delete the order from the session
		$DELETE_ORDER_SQL= " DELETE FROM `cart` WHERE `ct_session_id` = '".$_SESSION['username']."' "; /// REMOVE
		$result = $DB->selectQuery($DELETE_ORDER_SQL);
		
		// update the ordered filed in the login_in_record
		$UPDATE_SQL = "UPDATE `login_in_record` SET `ordered` = `ordered` + 1 WHERE `session_id` = '".$_SESSION['ct_session_id']."';";
		$result = $DB->selectQuery($UPDATE_SQL);
		
		return true;
		}
	
	}
	
	function sendorder($ORDERARRAY, $USEROBJ){
	require_once(SITEBASE."system/classes/class.phpmailer.php");
	
	$address = $USEROBJ->address1."\n".$USEROBJ->address2."\n".$USEROBJ->city."\n".$USEROBJ->postcode;
	
	
	$table = "<p>".$_SESSION['username']."</p><p>".$_SESSION['lob']."</p><p>".$address."</p><p>".$USEROBJ->email."</p>";
	
	
	foreach ($ORDERARRAY as $key){
	
	
		$table .= "<p>$key->nameOfPromotion</p>";
		
		$table .= "<p>Purchase Order Number: ".$this->getPurchaseOrderNumber()."</p>";
		$imageArray = $key->images;
		$table .= "<p>$imageArray[0]</p>";

		$promoItems = $key->promotionalItems;
		$extras = $key->extras;
		
		
		
			foreach ($promoItems as $promoKey => $promoVal ){
				if($promoVal[0] > 0){
					$table .= "<p>$promoKey : $promoVal[0] : &pound;$promoVal[1]</p>";
				}
			}
		
		
		$table .= "<p>------------------------------------------</p>";
		
		
		if( is_array($extras) ){
		
			foreach ($extras as $extraKey => $extraVal) {
				$table .="<p>$extraKey : $extraVal</p>";
			}
		}
		
		$table .= "<p>------------------------------------------</p><br/><br/>";
	
	}
	
	
	//   create invoice PDF  //
	$this->createpdf($ORDERARRAY, $address);
	
	
	// send the email
	$mail = new PHPMailer();
	$mail->IsSMTP();  // set mailer to use SMTP
	//$mail->Host = "post.toucan.uk.com";  // specify main and backup server
	$mail->Host = "87.106.246.179";  // specify main and backup server
	$mail->SMTPAuth = true;     // turn on SMTP authentication
	$mail->Username = "carl@caramba-marketing.co.uk";  // SMTP username
	$mail->Password = "wells"; // SMTP password
	$mail->From = "amanda@caramba-marketing.co.uk";
	$mail->FromName = "Order from ".SITENAME." Website";
	$mail->AddAddress("amanda@caramba-marketing.co.uk", "Carl");
	//$mail->AddAddress($_SESSION['userEmail'], $_SESSION['realName']);
	//$mail->AddReplyTo($_SESSION['userEmail'], $_SESSION['realName']);
	$mail->WordWrap = 80;                                 // set word wrap to 80 characters
	$mail->IsHTML(true);                                  // set email format to HTML
	$mail->Subject = "Order from ".SITENAME." Website";	
	$mail->Body    = $table;
	$mail->AltBody = $table;
	
//	var_dump($this->orderIds);
	
	foreach ($this->pdfs as $key => $val){
		$mail->AddAttachment($val);
	}
	return ($mail->Send());
	}
	
function createpdf($ORDERARRAY, $address){

	

	require('system/fpdf/fpdf.php');
	$this->pdfs = array();
	$counter = 0;
	foreach ($ORDERARRAY as $key){

		$pdf=new FPDF();
		$pdf->AddPage();
		$pdf->SetTextColor(0, 158, 219);
		$pdf->SetFont('Arial','B',20);
		$pdf->Cell(0,10,'INVOICE',0,1);
		$pdf->SetTextColor(0, 0, 0);
		$pdf->SetFont('Arial','',12);
		$pdf->Cell(20,10,'No:',0,0);
		$pdf->Cell(20,10,$this->orderIds[$counter],0,1);
		$pdf->Cell(20,10,'Date:',0,0);
		$pdf->Cell(20,10,date("d F Y", time()),0,1);
		$pdf->MultiCell(60,8, $address ,1,1);
		$pdf->SetFont('Arial','B',14);
		$pdf->Cell(0,10,$ORDERARRAY['nameOfPromotion'],0,1);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,10,$key->nameOfPromotion,0,1);
		$pdf->SetFont('Arial','',12);	
		$promoItems = $key->promotionalItems;
		$pdf->SetDrawColor(169, 187, 194);
			foreach ($promoItems as $promoKey => $promoVal ){
				if($promoVal[0] > 0){
				$pdf->Cell(150,10,"$promoKey x $promoVal[0]",'L B R');
				//$pdf->SetX(155);
				$pdf->Cell(40,10,"�".$promoVal[1],'L B R',1,"R");
			//	$pdf->Ln();
				//$pdf_table .= "$promoKey x $promoVal[0] : $promoVal[1]\n";
				}
			}		
		  
	$pdf->Cell(130,10,"payment terms: Strictly 30 days from date of invoice",0,0);
	$pdf->Cell(20,10,"Amount",0,0,"L");
	$pdf->Cell(40,10,"�".$key->totalCost,0,1,"R");
	
	$pdf->Cell(130,10,"",0,0);
	$pdf->Cell(20,10,"V.A.T. @ 15%",0,0,"L");
	$vatamount = ( (15 / 100) * $key->totalCost);
	$pdf->Cell(40,10,"�".number_format($vatamount,2),0,1,"R");
	
	$totalAmount = $key->totalCost + $vatamount;
	
	$pdf->SetFont('Arial','B',12);
	$pdf->Cell(130,10,"",0,0);
	$pdf->Cell(20,10,"Total Amount",0,0,"L");
	$pdf->Cell(40,10,"�".number_format($totalAmount,2) ,0,1,"R");
	
	//$pdf->Cell(104,10,"",1,0);
	//$pdf->Cell(6,10,"V.A.T @ 15%",'L B R',0);
	//$pdf->Cell(6,10,"�VAT AMOUNT",1,1,"R");
	
	//$pdf->Cell(104,10,"",1,0);
	//$pdf->Cell(6,10,"Total Amount",'L B R',0);
	//$pdf->Cell(6,10,"�TOTAL AMOUNT",1,1,"R");
	//$pdf->MultiCell(0,10,$pdf_table,0,1);
	$nameOfPdf = "Invoice_".$this->orderIds[$counter].".pdf";
	
	$pdf->Output($nameOfPdf, F);
	$this->pdfs[] = $nameOfPdf;
	$counter++;
	}
	
	}

}
	
	






?>